﻿using System.Security;
using System.Security.Permissions;
using System.Windows.Forms;
using System;

namespace ManagedSandbox
{
    public partial class FileDialogPermissionForm : Form, IPermissionEditor
    {
        public IPermission Permission { get; private set; }

        public FileDialogPermissionForm()
        {
            InitializeComponent();
        }

        public void Initialize(IPermission permission)
        {
            Permission = permission;

            foreach (var item in Enum.GetValues(typeof(FileDialogPermissionAccess)))
            {
                fileDialogPermissionAccessComboBox.Items.Add(item);
            }

            fileDialogPermissionAccessComboBox.SelectedIndex = 0;

            var fileDialogPermission = Permission as FileDialogPermission;

            if (null == fileDialogPermission)
                return;

            if (fileDialogPermission.IsUnrestricted())
            {
                unrestrictedCheckBox.Checked = true;
                permissionPanel.Enabled = false;
            }
            else
                fileDialogPermissionAccessComboBox.SelectedItem = fileDialogPermission.Access;
        }

        public CheckState GetCheckState()
        {
            var fileDialogPermission = Permission as FileDialogPermission;

            if (null == fileDialogPermission)
                return CheckState.Unchecked;

            if (fileDialogPermission.IsUnrestricted())
                return CheckState.Checked;

            return (FileDialogPermissionAccess.None == fileDialogPermission.Access) ?
                CheckState.Unchecked : CheckState.Indeterminate;
        }

        private void unrestrictedCheckBoxCheckedChanged(object sender, EventArgs e)
        {
            permissionPanel.Enabled = !unrestrictedCheckBox.Checked;
        }

        private void okButtonClick(object sender, EventArgs e)
        {
            Permission = unrestrictedCheckBox.Checked
                             ? new FileDialogPermission(PermissionState.Unrestricted)
                             : new FileDialogPermission(
                                   (FileDialogPermissionAccess) fileDialogPermissionAccessComboBox.SelectedItem);

            DialogResult = DialogResult.OK;
        }
    }
}
